<?php
namespace app\common\exception;

use Exception;
use think\exception\Handle;
use think\exception\HttpException;
use think\exception\ValidateException;
use think\Request;

class Http extends Handle
{

    public function render(Exception $e)
    {
        // 参数验证错误
        if ($e instanceof ValidateException) {
            return json($e->getError(), 200);
        }

        // 请求异常
        if ($e instanceof HttpException && request()->isAjax()) {
            return response($e->getMessage(), $e->getStatusCode());
        }

        //如果开启调试走正常流程
        if (config('app_debug') === true) {
            return parent::render($e);
        }
        //写入错误日志
        $request = Request::instance();
        trace('Exception Error.
        ip:'.$request->ip().'
        method:'.$request->method().'
        type:'.$request->type().'
        param:'.json_encode($request->param()).' 
        ajax:'.var_export($request->isAjax(), true).' 
        url:'.$request->url(true).'  
        date:'.date('YmdHis').' 
        file:'.$e->getFile().'
        line:'.$e->getLine().'
        error:'.$e->getMessage(),'error');
        //输出错误
        return json(['code'=>500,'msg'=>'Sorry,we make a mistake,please contact us .'.date('YmdHis')],200);
    }

}